package com.qire.antscompiler;

import com.google.auto.service.AutoService;
import com.qire.antscompiler.generator.InterceptorCodeGenerator;
import com.qire.antscompiler.utils.Log;
import com.qire.antscore.annotation.InterceptorMapping;
import com.qire.antscore.common.AssertUtils;
import com.qire.antscore.constant.ProcessorConfig;

import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

/**
 * 拦截器注解解析代码生成器，负责生成拦截器相关代码
 */
@AutoService(Processor.class)
@SupportedOptions(ProcessorConfig.OPTIONS_MODULE_NAME)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes(ProcessorConfig.ANNOTATION_TYPE_INTERCEPTOR)
public class InterceptorProcessor extends AbstractProcessor {

    private Log log;

    private InterceptorCodeGenerator codeGenerator;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        log = Log.newLog(processingEnv.getMessager());

        String moduleName = "";
        Map<String, String> options = processingEnv.getOptions();
        if (AssertUtils.notEmpty(options)) {
            moduleName = options.get(ProcessorConfig.OPTIONS_MODULE_NAME);
        }

        codeGenerator = new InterceptorCodeGenerator(processingEnv,moduleName);
        log.i("init InterceptorProcessor " + moduleName + " success !");
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (AssertUtils.notEmpty(annotations)) {
            Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(InterceptorMapping.class);
            try {
                codeGenerator.parseInterceptor(elements);
            } catch (Exception e) {
                log.i(e.getMessage());
            }
            return true;
        }
        return false;
    }

}
